<template>
  <div class="guard-schedule-content">
    <el-card>
      <div class="search-bar">
        <el-input v-model="searchClassName" placeholder="班次名称" style="width: 200px; margin-right: 10px;" />
        <el-select v-model="searchGuardPointId" placeholder="护导点" style="width: 200px; margin-right: 10px;">
          <el-option v-for="item in signPointList" :key="item.id" :label="item.pointName" :value="String(item.id)" />
        </el-select>
        <el-button type="primary" @click="fetchData">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" style="float: right;" @click="openAddDialog">+ 添加班次</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%; margin-top: 10px;">
        <el-table-column prop="className" label="班次名称" />
        <el-table-column prop="guardPointName" label="护导点" />
        <el-table-column v-for="day in weekDays" :key="day" :label="day">
          <template #default="scope">
            <div v-if="scope.row.schedules[day]">
              带班人: {{ scope.row.schedules[day].leaderName || '-' }}<br>
              护导人: {{ scope.row.schedules[day].guardName || '-' }}
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button size="small" @click="edit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        style="margin-top: 20px; text-align: right;"
        @current-change="fetchData"
      />
    </el-card>
    <el-dialog v-model="showAddDialog" :title="editForm.id ? '编辑班次' : '添加班次'" width="600px">
      <el-form :model="editForm" label-width="100px" ref="formRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="班次名称" prop="className">
              <el-input v-model="editForm.className" placeholder="请输入班次名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="护导点" prop="guardPointId">
              <el-select v-model="editForm.guardPointId" placeholder="请选择护导点">
                <el-option v-for="item in signPointList" :key="item.id" :label="item.pointName" :value="String(item.id)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-for="day in weekDays" :key="day" style="margin-bottom: 12px; display: flex; align-items: center;">
          <strong style="width: 40px;">{{ day }}</strong>
          <el-input
            v-model="editForm.schedules[day].leaderName"
            placeholder="带班人"
            style="width: 120px; margin: 0 8px;"
            readonly
            @click="openUserDialog(day, 'leaderName')"
          />
          <el-input
            v-model="editForm.schedules[day].guardName"
            placeholder="护导人"
            style="width: 120px; margin-right: 8px;"
            readonly
            @click="openUserDialog(day, 'guardName')"
          />
        </div>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </template>
    </el-dialog>
    <!-- 选择人员弹窗 -->
    <el-dialog v-model="showUserDialog" title="选择人员" width="600px">
      <div style="margin-bottom: 10px;">
        <el-input v-model="userSearchName" placeholder="用户名" style="width: 180px; margin-right: 10px;" />
        <el-input v-model="userSearchPhone" placeholder="手机号" style="width: 180px; margin-right: 10px;" />
        <el-button type="primary" @click="fetchUserList">查询</el-button>
      </div>
      <el-table :data="userList" style="width: 100%;" @row-click="handleUserRowClick">
        <el-table-column label="单选" width="60">
          <template #default="scope">
            <el-radio v-model="selectedUserId" :label="scope.row.id" />
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="姓名">
          <template #default="scope">
            {{ scope.row.realName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="departmentName" label="所属部门">
          <template #default="scope">
            {{ scope.row.departmentName || '-' }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="showUserDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmUserSelect">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
const searchClassName = ref('')
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showAddDialog = ref(false)
const formRef = ref(null)
const showUserDialog = ref(false)
const userList = ref([])
const userSearchName = ref('')
const userSearchPhone = ref('')
const selectedUserId = ref(null)
const currentUserSelectDay = ref('')
const currentUserSelectRole = ref('')
const signPointList = ref([])
const searchGuardPointId = ref('')

const defaultSchedules = () => {
  const obj = {}
  weekDays.forEach(day => {
    obj[day] = { leaderName: '', guardName: '', leaderId: '', guardId: '' }
  })
  return obj
}
const editForm = ref({
  id: null,
  className: '',
  schoolName: '',
  guardPointId: '',
  schedules: defaultSchedules()
})

function fetchData() {
  fetch(`/api/guard/schedule/list?className=${encodeURIComponent(searchClassName.value)}&guardPointId=${searchGuardPointId.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`)
    .then(res => res.json())
    .then(data => {
      // 按className分组，合成为前端表格需要的结构
      const groupMap = {}
      ;(data.records || []).forEach(item => {
        if (!groupMap[item.className]) {
          groupMap[item.className] = {
            id: item.id, // 取第一个id
            className: item.className,
            guardPointId: item.guardPointId, // 关键：加上护导点ID
            guardPointName: item.guardPointName,
            schedules: {}
          }
        }
        groupMap[item.className].schedules[item.weekDay] = {
          leaderName: item.leaderName || '',
          guardName: item.guardName || '',
          leaderId: item.leaderId,
          guardId: item.guardId,
          startTime: item.startTime || '',
          endTime: item.endTime || ''
        }
      })
      tableData.value = Object.values(groupMap)
      total.value = data.total || 0
    })
    .catch(err => {
      ElMessage.error('获取排班列表失败')
    })
}

function reset() {
  searchClassName.value = ''
  searchGuardPointId.value = ''
  fetchData()
}

function openAddDialog() {
  editForm.value = {
    id: null,
    className: '',
    schoolName: '',
    guardPointId: '',
    schedules: defaultSchedules()
  }
  showAddDialog.value = true
}

async function edit(row) {
  // 获取一周所有排班（同班次、同护导点）
  const res = await fetch(`/api/guard/schedule/list?className=${encodeURIComponent(row.className)}&guardPointId=${row.guardPointId}`)
  const data = await res.json()
  const schedules = defaultSchedules()
  ;(data.records || []).forEach(item => {
    schedules[item.weekDay] = {
      id: item.id,
      leaderName: item.leaderName || '',
      guardName: item.guardName || '',
      leaderId: item.leaderId,
      guardId: item.guardId,
      startTime: item.startTime || '',
      endTime: item.endTime || ''
    }
  })
  editForm.value = {
    id: row.id, // 只用于判断编辑/新增
    className: row.className,
    guardPointId: String(row.guardPointId || ''),
    schedules
  }
  showAddDialog.value = true
}

function del(row) {
  ElMessageBox.confirm('确定要删除该班次吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    fetch('/api/guard/schedule/delete', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify([row.className])
    })
      .then(res => {
        if (!res.ok) throw new Error('删除失败')
        return res
      })
      .then(() => {
        ElMessage.success('删除成功')
        fetchData()
      })
      .catch(err => {
        ElMessage.error('删除失败')
      })
  })
}

async function save() {
  if (!editForm.value.className) {
    ElMessage.warning('请输入班次名称')
    return
  }
  if (!editForm.value.guardPointId) {
    ElMessage.warning('请选择护导点')
    return
  }
  const payloads = []
  for (const day of weekDays) {
    const schedule = editForm.value.schedules[day]
    if (schedule.leaderName || schedule.guardName) {
      payloads.push({
        id: schedule.id, // 编辑时有id，新增时无id
        guardPointId: editForm.value.guardPointId,
        className: editForm.value.className,
        weekDay: day,
        leaderId: schedule.leaderId, // 关键
        guardId: schedule.guardId,   // 关键
        leaderName: schedule.leaderName,
        guardName: schedule.guardName
      })
    }
  }
  if (payloads.length === 0) {
    ElMessage.warning('请至少填写一天的带班人或护导人')
    return
  }
  console.log('payloads', payloads)
  const url = editForm.value.id ? '/api/guard/schedule/batch-save' : '/api/guard/schedule/batch-add'
  try {
    await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payloads)
    })
    showAddDialog.value = false
    ElMessage.success(editForm.value.id ? '更新成功' : '添加成功')
    fetchData()
  } catch (err) {
    ElMessage.error('操作失败')
  }
}

function openUserDialog(day, role) {
  currentUserSelectDay.value = day
  currentUserSelectRole.value = role
  selectedUserId.value = null
  showUserDialog.value = true
  fetchUserList()
}

function fetchUserList() {
  fetch('/api/security-guard-user/list', {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' }
  })
    .then(res => res.json())
    .then(data => {
      const list = Array.isArray(data) ? data : (data.data || [])
      // 前端筛选
      userList.value = list.filter(user => {
        const matchName = !userSearchName.value || user.real_name.includes(userSearchName.value)
        const matchPhone = !userSearchPhone.value || user.phone.includes(userSearchPhone.value)
        return matchName && matchPhone
      })
    })
    .catch(err => {
      console.error(err)
      ElMessage.error('获取保安用户列表失败')
    })
}

function handleUserRowClick(row) {
  selectedUserId.value = row.id
}

function confirmUserSelect() {
  const user = userList.value.find(u => u.id === selectedUserId.value)
  if (user && currentUserSelectDay.value && currentUserSelectRole.value) {
    editForm.value.schedules[currentUserSelectDay.value][currentUserSelectRole.value] = user.realName
    // 新增：同时存id
    if (currentUserSelectRole.value === 'leaderName') {
      editForm.value.schedules[currentUserSelectDay.value].leaderId = user.id
    } else if (currentUserSelectRole.value === 'guardName') {
      editForm.value.schedules[currentUserSelectDay.value].guardId = user.id
    }
  }
  showUserDialog.value = false
}

function fetchSignPointList() {
  fetch('/api/guard/point/list')
    .then(res => res.json())
    .then(data => {
      signPointList.value = data.records || []
    })
    .catch(err => {
      ElMessage.error('获取护导点列表失败')
    })
}

watch(showAddDialog, (val) => {
  if (!val) {
    editForm.value = {
      id: null,
      className: '',
      schoolName: '',
      guardPointId: '',
      schedules: defaultSchedules()
    }
  }
})

onMounted(() => {
  fetchSignPointList()
  fetchData()
})
</script>

<style scoped>
.guard-schedule-content {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
</style>
